import { observable, action, toJS } from 'mobx';
import { WeaTableNew, WeaForm } from 'comsMobx';
// import { TableStore } from '../../../coms/wea-table-new';
// import { WeaForm } from '../../../coms/wea-form';
import * as API from '../../apis/common';

// import treeDatas from './treeDatas';
const { TableStore } = WeaTableNew;
import { WeaLocaleProvider, WeaTools } from 'ecCom';
// import { WeaIntro, WeaLocaleProvider } from 'ecCom';
// const { Intro } = WeaIntro;
const getLabel = WeaLocaleProvider.getLabel;

import { isObject, isFunction } from 'lodash';

export class ComsStore {
  @observable title = getLabel(132039, '查阅文档');
  @observable loading = false;
  @observable treeLoading = false;
  @observable conditionLoading = false;
  @observable rightMenuLoading = false;
  // table
  @observable dataKey = '';
  @observable comsWeaTableStore = new TableStore();
  // tree
  @observable treeDatas = [];
  @observable treeTypes = [];
  @observable treeCounts = {};
  // conditions
  @observable conditioninfo = [];
  // rightMenu
  @observable rightMenu = [];
  // form
  @observable form = new WeaForm();
  // 要获取目录下文档数字的目录id
  @observable treeSecids='';
  // 记录已经请求过的目录id，避免二次请求
  @observable secidSet=new Set();

  constructor() {
    this.doLoading = this.doLoading.bind(this);
    this.doSearch = this.doSearch.bind(this);
    this.getTreeDatas = this.getTreeDatas.bind(this);
    this.getConditionInfo = this.getConditionInfo.bind(this);
    this.getRightMenu = this.getRightMenu.bind(this);
    this.setConditionInfo = this.setConditionInfo.bind(this);
  }

  @action
  setConditionInfo(conditioninfo) {
    this.conditioninfo = conditioninfo;
  }

  @action
  doLoading(bool = false) {
    this.loading = bool;
    return this;
  }

  @action
  doSearch(module, params = {}) {
    this.loading = true;
    API.doSearch(module, params).then(action((data) => {
      this.comsWeaTableStore.getDatas(data.sessionkey, params.current || 1);
      this.dataKey = data.sessionkey;
      this.loading = false;
    }));
    return this;
  }

  @action
  initTreeNumData=() => {
    this.secidSet.clear();
    this.treeSecids = '';
  }

  @action
  getTreeDatas(module, params = {}, cb) {
    this.treeLoading = true;
    // 查阅文档，请求全部，有local，非预加载情况下，先直接读取一次local数据
    let storagedTree = localStorage[`weaDocSearchTree_${params.viewcondition}`];
    if (module === 'Search' && params.isFav !== '1' && params.viewcondition !== undefined
      && storagedTree && !params.preLoad) {
      try {
        this.treeDatas = storagedTree ? JSON.parse(storagedTree) : [];
      } catch (ex) {
        this.treeDatas = [];
      }
    }
    API.getTreeDatas(module, { ...params, firstSecid: '1' }).then(action((data) => {
      const { treedata, countcfg, treecount } = data;
      if (module === 'Search') {
        let treeSecids = '';
        treedata.forEach((val) => {
          treeSecids = treeSecids == '' ? val.key : (`${treeSecids},${val.key}`);
        });
        this.treeSecids = treeSecids;
        this.getTreeNums(module, { ...params, secid: treeSecids });
      }
      // if (!params.preLoad) {
        this.treeDatas = treedata;
        if (countcfg) this.treeTypes = countcfg;
        if (treecount) this.treeCounts = treecount;
      // }
      // local 缓存全部目录树
      if (module === 'Search' && params.isFav !== '1' && params.viewcondition !== undefined) {
        localStorage.setItem(`weaDocSearchTree_${params.viewcondition}`, JSON.stringify(treedata));
      }
      this.treeLoading = false;
      if (treedata.length === 0 && params.isFav === '1' && params.viewcondition !== undefined) {
        const nowDate = new Date();
        const doIntro = () => {
          // const intro = new Intro();
          const intro = window.document_intro;
          if (!intro) {
              return;
          }
          intro.setOptions({
            steps: [
              {
                element: '#document_step1',
                intro: getLabel(385089, '还没有收藏目录，点击这里可以打开全部目录'),
              },
              {
                element: '#document_step2',
                intro: getLabel(385088, '鼠标移动到条目上，点击收藏 ☆ 就能添加到我的收藏列表了'),
              },
            ],
          });
          intro.onchange((ele) => {
            if (ele.getAttribute('data-step') === '2') {
              // 加载全部目录树本地数据
              if (localStorage[`weaDocSearchTree_${params.viewcondition}`]
                && !sessionStorage.wea_Doc_hasShowIntro) {
                this.treeDatas =
                  JSON.parse(localStorage[`weaDocSearchTree_${params.viewcondition}`]);
              } else {
                this.getTreeDatas(module, { ...params, isFav: '0' })
                  .getTreeNums(module, { ...params, isFav: '0' });
              }
            }
          });
          const doRevert = () => this.getTreeDatas(module, { ...params })
            .getTreeNums(module, { ...params });
          intro.oncomplete(() => {
            doRevert();
          });
          intro.onexit(() => {
            doRevert();
          });
          intro.start();
          sessionStorage.setItem('wea_Doc_hasShowIntro', nowDate.toLocaleDateString());
        };
        if (sessionStorage.wea_Doc_hasShowIntro) {
          const lastDate = new Date(sessionStorage.wea_Doc_hasShowIntro);
          if (nowDate - lastDate > 3600 * 1000 * 24 * 3) {
            doIntro();
          }
        } else {
          doIntro();
        }
      }
      isFunction(cb) && cb();
    }));
    return this;
  }

  @action
  getTreeNums(module, params = {}) {
    let selectChild = params && params.selectChild;
    let secid = params && params.secid;
    (this.secidSet.has(secid) || !secid) ? '' :
    API.getTreeNums(module, params).then(action((data) => {
      const { countcfg, treecount } = data;
      this.treeTypes = countcfg;
      this.treeCounts = { ...toJS(this.treeCounts), ...treecount };
      if (selectChild == '1' && module == 'Search') {
        this.secidSet.add(secid);
      }
    }));
    return this;
  }

  @action
  getRightMenu(module, params = {}) {
    this.rightMenuLoading = true;
    API.getRightMenu(module, params).then(action((data) => {
      this.rightMenu = data.rightMenus;
      this.rightMenuLoading = false;
    }));
    return this;
  }

  @action
  getConditionInfo(module, params = {}, cb) {
    this.conditionLoading = true;
    let apiParams = params;

    if (params.seccategory && params.seccategory.value) {
    	apiParams = { ...params, seccategory: params.seccategory.value };
    }

    API.getConditionInfo(module, apiParams).then(action((data) => {
      this.conditionLoading = false;
      const { isFormInit } = this.form;
      if (isFormInit) {
        // 如果初始化过表单，需要重新初始化一份表单，并在同一周期置空数据
        // 需要暂存数据的可以考虑多份 ComsStore 继承
        this.form = new WeaForm();
        this.conditioninfo = [];
      }
      this.conditioninfo = data.condition;
      this.form.initFormFields(data.condition);
      const keys = Object.keys(params);
      if (keys.length > 1 && this.form.isFormInit) {
        const fields = {};
        keys.forEach((key) => {
          if (key !== 'viewcondition' && key !== 'groupid') {
            isObject(params[key]) ? (
              fields[key] = params[key]
            ) : (
              fields[key] = { value: params[key] }
            );
          }
        });
        this.form.updateFields(fields);
        isFunction(cb) && cb(this.form.getFormParams());
      }
    }));
    return this;
  }

  getFormParams() {
    return this.form.getFormParams();
  }
}
